<template>
  <view class="recommend-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-search-bar 
        @click="handleSearch" 
        placeholder="搜索菜品或食材"
        :focus="false"
        :show-action="false"
        :radius="50"
      />
    </view>

    <!-- 推荐菜品列表 -->
    <view class="recommend-list">
      <view class="section-title">混合推荐结果</view>
      <view class="dish-grid">
        <view 
          class="dish-item" 
          v-for="dish in recommendList" 
          :key="dish.id"
          @click="viewDishDetail(dish.id)"
        >
          <image :src="dish.image" class="dish-image" mode="aspectFill" />
          <view class="dish-info">
            <text class="dish-name">{{ dish.name }}</text>
            <view class="dish-meta">
              <uni-rate :value="dish.rating" :readonly="true" :size="12" />
              <text class="rating-text">{{ dish.rating }}</text>
            </view>
            <view class="dish-tags">
              <text class="tag" v-for="tag in dish.tags" :key="tag">{{ tag }}</text>
              <text class="tag portion" v-if="dish.portion">份量: {{ dish.portion }}</text>
              <text class="tag calories" v-if="dish.calories">热量: {{ dish.calories }}</text>
            </view>
            <view class="dish-status">
              <text class="status-tag favorited" v-if="dish.isFavorited">♥ 已收藏</text>
              <text class="status-tag rated" v-if="dish.userRating > 0">★ 已评分({{ dish.userRating }}分)</text>
            </view>
            <view class="dish-actions">
              <button 
                class="action-btn" 
                @click.stop="toggleFavorite(dish)"
                :class="{ 'favorited': dish.isFavorited }"
              >
                {{ dish.isFavorited ? '已收藏' : '收藏' }}
              </button>
              <button 
                class="action-btn rate" 
                @click.stop="showRateDialog(dish)"
                :class="{ 'rated': dish.userRating > 0 }"
              >
                {{ dish.userRating > 0 ? `已评分(${dish.userRating}分)` : '评分' }}
              </button>
              <button class="action-btn primary" @click.stop="viewNutritionDetail(dish)">
                详情
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <uni-load-more :status="loadStatus" />
  </view>
</template>

<script>
import { getHybridRecommendation, toggleFavorite, recordClick, rateDish, getUserDishStatus } from '@/api/diet'

export default {
  data() {
    return {
      recommendList: [],
      loadStatus: 'more',
      pageNum: 1,
      pageSize: 10
    }
  },
  onLoad() {
    console.log('📱 页面加载开始')
    // 检查登录状态，如果未登录则模拟登录
    this.checkLoginStatus()
    this.loadRecommendList()
  },
  onReachBottom() {
    if (this.loadStatus === 'more') {
      this.loadMore()
    }
  },
  methods: {
    async loadRecommendList() {
      console.log('🚀 开始加载混合推荐列表...')
      try {
        this.loadStatus = 'loading'
        const userId = this.getUserId()
        console.log('👤 当前用户ID:', userId)
        
        const res = await getHybridRecommendation(userId)
        console.log('🔍 混合推荐API完整返回数据:', res)
        
        if (res && res.final_recommendation && res.final_recommendation.recommended_dishes) {
          this.processDishes(res.final_recommendation.recommended_dishes)
        } else if (res && res.recommended_dishes) {
          this.processDishes(res.recommended_dishes)
        } else if (res && res.mopso_result && res.mopso_result.selected_dishes) {
          this.processDishes(res.mopso_result.selected_dishes, 'mopso')
        } else if (res && Array.isArray(res)) {
          this.processDishes(res)
        } else {
          console.log('❌ 未找到推荐菜品数据')
          this.showTestData()
        }
        
        this.loadStatus = 'noMore'
      } catch (error) {
        console.error('❌ 加载混合推荐失败:', error)
        this.loadStatus = 'more'
        uni.showToast({ title: '加载失败', icon: 'none' })
        this.showTestData()
      }
    },
    
    processDishes(dishesData, type = 'normal') {
      console.log('🔄 开始处理菜品数据, 类型:', type)
      
      const dishes = dishesData.map((item, index) => {
        let dishId, dishName, imgUrl, portionG, calories
        if (type === 'mopso') {
          dishId = item.dish_id
          dishName = item.dish_name
          imgUrl = item.img_url
          portionG = item.portion_g
          calories = item.calories
        } else {
          dishId = item.dish_id || item.id
          dishName = item.dish_name || item.name
          imgUrl = item.img_url || item.image
          portionG = item.portion_g || item.portion
          calories = item.calories
        }
        
        let imageUrl = `/static/images/default-dish.jpg`
        if (imgUrl) {
          if (imgUrl.startsWith('http')) {
            imageUrl = imgUrl
          } else {
            imageUrl = `http://localhost:8080${imgUrl}`
          }
        }
        
        return {
          id: dishId,
          name: dishName || '未知菜品',
          rating: 5.0,
          image: imageUrl,
          tags: ['营养均衡', '个性化', '智能推荐'],
          isFavorited: false,
          userRating: 0,
          portion: portionG ? portionG + 'g' : '100g',
          calories: calories ? calories + '千卡' : '0千卡'
        }
      })
      
      this.recommendList = dishes
      // 获取用户状态
      this.loadUserStatus()
    },
    
    showTestData() {
      this.recommendList = [
        {
          id: 1,
          name: '测试菜品1',
          rating: 4.5,
          image: '/static/images/default-dish.jpg',
          tags: ['测试', '营养均衡'],
          isFavorited: false,
          userRating: 0,
          portion: '150g',
          calories: '200千卡'
        },
        {
          id: 2,
          name: '测试菜品2',
          rating: 4.8,
          image: '/static/images/default-dish.jpg',
          tags: ['测试', '个性化'],
          isFavorited: false,
          userRating: 0,
          portion: '120g',
          calories: '180千卡'
        }
      ]
      // 获取用户状态
      this.loadUserStatus()
    },
    
    loadMore() {
      this.pageNum++
      this.loadRecommendList()
    },
    
    handleSearch() {
      uni.navigateTo({
        url: '/pages/diet/search/index'
      })
    },
    
    async viewDishDetail(dishId) {
      console.log('👁️ 点击菜品详情, ID:', dishId)
      
      try {
        const userId = this.getUserId()
        await this.recordClick(dishId, userId)
      } catch (error) {
        console.error('❌ 记录点击失败:', error)
      }
      
      uni.navigateTo({
        url: `/pages/diet/detail/index?id=${dishId}`
      })
    },
    
    checkLoginStatus() {
      const userId = uni.getStorageSync('userId')
      console.log('🔍 检查登录状态 - userId:', userId)
      
      if (!userId) {
        console.log('🔑 设置默认用户ID')
        uni.setStorageSync('userId', 100)
      }
    },
    
    getUserId() {
      let userId = uni.getStorageSync('userId')
      
      if (!userId || userId === 'undefined' || isNaN(userId)) {
        userId = 100
        uni.setStorageSync('userId', userId)
        console.log('⚠️ 设置默认用户ID:', userId)
      }
      
      return Number(userId)
    },
    
    async recordClick(dishId, userId) {
      try {
        const result = await recordClick(dishId, userId)
        console.log('✅ 点击记录结果:', result)
      } catch (error) {
        console.error('❌ 点击记录失败:', error)
      }
    },
    
    async toggleFavorite(dish) {
      console.log('⭐ 开始收藏操作...')
      
      try {
        const userId = this.getUserId()
        console.log('👤 用户ID:', userId)
        console.log('🍽️ 菜品ID:', dish.id)
        
        const result = await toggleFavorite(dish.id, userId)
        console.log('✅ 收藏API返回结果:', result)
        
        // 根据后端返回的isFavorited状态更新UI
        dish.isFavorited = result.data?.isFavorited !== undefined ? result.data.isFavorited : !dish.isFavorited
        
        uni.showToast({
          title: dish.isFavorited ? '收藏成功' : '取消收藏',
          icon: 'success'
        })
      } catch (error) {
        console.error('❌ 收藏操作失败:', error)
        uni.showToast({ 
          title: '操作失败: ' + error.message, 
          icon: 'none' 
        })
      }
    },
    
    showRateDialog(dish) {
      uni.showActionSheet({
        itemList: ['⭐⭐⭐⭐⭐ 5分', '⭐⭐⭐⭐ 4分', '⭐⭐⭐ 3分', '⭐⭐ 2分', '⭐ 1分'],
        success: (res) => {
          const rating = 5 - res.tapIndex // 5,4,3,2,1
          this.rateDish(dish, rating)
        }
      })
    },
    
    async rateDish(dish, rating) {
      if (dish.userRating > 0) {
        uni.showToast({ 
          title: '您已对该菜品评过分了', 
          icon: 'none' 
        })
        return
      }
      
      try {
        const userId = this.getUserId()
        console.log('⭐ 开始评分操作:', { dishId: dish.id, userId, rating })
        
        const result = await rateDish({ dishId: dish.id, userId, rating })
        console.log('✅ 评分结果:', result)
        
        // 更新本地状态
        dish.userRating = rating
        
        uni.showToast({
          title: `评分成功: ${rating}分`,
          icon: 'success'
        })
      } catch (error) {
        console.error('❌ 评分失败:', error)
        uni.showToast({ 
          title: '评分失败', 
          icon: 'none' 
        })
      }
    },
    
    viewNutritionDetail(dish) {
      uni.showModal({
        title: `${dish.name} 营养信息`,
        content: `推荐份量: ${dish.portion}\n热量: ${dish.calories}\n\n该菜品经过UPICF+MOPSO混合算法优化，既符合您的个人偏好，又能满足营养需求。`,
        showCancel: false,
        confirmText: '知道了'
      })
    },
    
    async loadUserStatus() {
      try {
        const userId = this.getUserId()
        const dishIds = this.recommendList.map(dish => dish.id)
        if (dishIds.length === 0) return
        
        const res = await getUserDishStatus(userId, dishIds)
        if (res.code === 200) {
          const { favorites, ratings } = res.data
          this.recommendList.forEach(dish => {
            dish.isFavorited = favorites[dish.id] || false
            dish.userRating = ratings[dish.id] || 0
          })
        }
      } catch (error) {
        console.error('获取用户状态失败:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.recommend-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.dish-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.dish-item {
  width: 48%;
  background: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.dish-image {
  width: 100%;
  height: 200rpx;
}

.dish-info {
  padding: 20rpx;
}

.dish-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.dish-meta {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.rating-text {
  font-size: 24rpx;
  color: #666;
  margin-left: 10rpx;
}

.dish-tags {
  margin-bottom: 15rpx;
}

.dish-status {
  margin-bottom: 10rpx;
}

.status-tag {
  display: inline-block;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  margin-right: 8rpx;
  
  &.favorited {
    background: #ff4d4f;
    color: white;
  }
  
  &.rated {
    background: #52c41a;
    color: white;
  }
}

.tag {
  display: inline-block;
  background: #e8f4fd;
  color: #1890ff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  margin-right: 8rpx;
  
  &.portion {
    background: #f6ffed;
    color: #52c41a;
  }
  
  &.calories {
    background: #fff2e8;
    color: #fa8c16;
  }
}

.dish-actions {
  display: flex;
  justify-content: space-between;
}

.action-btn {
  flex: 1;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  border-radius: 30rpx;
  font-size: 24rpx;
  border: 1rpx solid #ddd;
  background: white;
  color: #666;
  margin: 0 3rpx;
  
  &.primary {
    background: #1890ff;
    color: white;
    border-color: #1890ff;
  }
  
  &.favorited {
    background: #ff4d4f;
    color: white;
    border-color: #ff4d4f;
  }
  
  &.rate {
    background: #faad14;
    color: white;
    border-color: #faad14;
  }
}
</style>